<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/28
 * Time: 13:59
 */

namespace App\Http\Logics\Admin;

use App\PartnerMessage;
use App\PartnerMessagePhoto;
use App\Http\Logics\BaseLogic;
class PartnerMessageLogic extends BaseLogic
{
    public static function createPartnerMessage($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $response = self::getPartnerIdByKey($data['key']);
        if ($response->code){
            return self::response($response->code);
        }
        $partner_id = $response->data;

        $partner_message = new PartnerMessage();
        $partner_message->user_id = $user_id;
        $partner_message->partner_id = $partner_id;
        $partner_message->content = $data['content'];
        if (!$partner_message->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        $photo_list_arr = json_decode($data['photo_list_str']);

        foreach ($photo_list_arr as $item){
            $cafe_message_photo = new PartnerMessagePhoto();
            $cafe_message_photo->url = $item->url;
            $cafe_message_photo->partner_message_id = $partner_message->id;
            if (!$cafe_message_photo->save()){
                return self::response(self::OBJECT_SAVE_FAIL);
            }
        }
        return self::response(self::SUCCESS);
    }

    public static function getPartnerMessageList($data)
    {
        $partner_message = PartnerMessage::where(function ($query) use ($data){
            if (!empty($data['key'])){
                $response = self::getPartnerIdByKey($data['key']);
                if ($response->code){
                    return self::response($response->code);
                }
                $partner_id = $response->data;
                $query->where('partner_id', $partner_id);
            }
            if (!empty($data['loginSession'])){
                $response = self::getUserIdByLoginSession($data['loginSession']);
                if ($response->code){
                    return self::response($response->code);
                }
                $user_id = $response->data;
                $query->where('user_id', $user_id);
            }
        })->orderBy('id', 'desc')->get();
        if (empty($partner_message)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $partner_message);
    }

    public static function getPartnerMessageDetail($data)
    {
        $partner_message = PartnerMessage::with(['partnerMessagePhoto'])->where('id', $data['partner_message_id'])->first();
        if (empty($partner_message)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $partner_message);
    }
}